<template>
  <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
    <el-tab-pane label="采购入库" name="first">
      <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="入库编号" prop="bpsSn">
            <el-input
              v-model="queryParams.bpsSn"
              placeholder="请输入入库编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
<!--          <el-col :span="1.5">-->
<!--            <el-button-->
<!--              type="primary"-->
<!--              plain-->
<!--              icon="el-icon-plus"-->
<!--              size="mini"-->
<!--              @click="handleAdd"-->
<!--              v-hasPermi="['mes:put_storage:add']"-->
<!--            >新增入库单</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button-->
<!--              type="success"-->
<!--              plain-->
<!--              icon="el-icon-edit"-->
<!--              size="mini"-->
<!--              :disabled="single"-->
<!--              @click="handleUpdate"-->
<!--              v-hasPermi="['mes:put_storage:edit']"-->
<!--            >修改</el-button>-->
<!--          </el-col>-->
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['mes:put_storage:export']"
            >导出</el-button>
          </el-col>
<!--          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
        </el-row>

        <el-table v-loading="loading" :data="put_storageList" border style="width: 100%" @selection-change="handleSelectionChange">
<!--          <el-table-column type="selection" width="55" align="center" />-->
<!--          <el-table-column label="序号" align="center" prop="number"width="90" />-->
          <el-table-column label="状态" align="center" prop="state"width="90" >
            <template v-slot = "scope">
              <dict-tag :options="dict.type.storage_put_status" :value="scope.row.state"/>
            </template>
          </el-table-column>
          <el-table-column label="入库类型" align="center" prop="bpsType">
            <template v-slot = "scope">
              <dict-tag :options="dict.type.storage_bpstype" :value="scope.row.bpsType"/>
            </template>
          </el-table-column>
          <el-table-column label="采购单号" align="center" prop="purchaseSn" />
<!--          <el-table-column label="供应商" align="center" prop="name" />-->
          <el-table-column label="入库单编号" align="center" prop="bpsSn" />
          <el-table-column label="需入库数量" align="center" prop="bpsNum" />
          <el-table-column label="创建者" align="center" prop="createdBy" />
          <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-check"
                @click="handleUpdate(scope.row,scope.$index)"
                v-hasPermi="['mes:put_storage:edit']"
              >入库</el-button>
<!--              <el-button-->
<!--                size="mini"-->
<!--                type="text"-->
<!--                icon="el-icon-delete"-->
<!--                @click="handleDelete(scope.row)"-->
<!--                v-hasPermi="['mes:put_storage:remove']"-->
<!--              >删除</el-button>-->
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改入库管理对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="1600px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-divider>物料列表</el-divider><!--分割线-->
            <el-form-item label="采购单号:" prop="purchaseSn">
                  <!--              <el-select v-model="form.orderId" placeholder="请选择采购单" @change="handleOrderChange">-->
                  <!--                <el-option-->
                  <!--                  v-for="item in orderList"-->
                  <!--                  :key="item.id"-->
                  <!--                  :label="`${item.name}/${item.sn}`"-->
                  <!--                  :value="item.id"-->
                  <!--                ></el-option>-->
                  <!--              </el-select>-->
              <span>{{form.purchaseSn}}</span>
            </el-form-item>
            <el-card shadow="always" style="border-radius: 15px;">
              <el-table border style="width: 100%" v-loading="loading" :data="orderMatList">
                <el-table-column label="物料名称" prop="matName" :width="80">
                </el-table-column>
                <el-table-column label="物料编码" prop="matSn">
                </el-table-column>
                <el-table-column label="供应商" prop="supplierName" :width="80">
                </el-table-column>
                <el-table-column label="物料库" prop="strmId">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.strmId" placeholder="请选择仓库" @change="handleStrmChange(scope.row)">
                      <el-option
                        v-for="item in storeroomList"
                        :key="item.id"
                        :label="`${item.name}/${item.sn}`"
                        :value="item.id"
                      ></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="仓库容量" prop="capacity" label-width="150px">
                  <template slot-scope="scope">
                   <el-row type="flex" align="middle">
                     <el-col :span="12">
                       <span>总容量:{{scope.row.strmNum}}</span>
                     </el-col>
                     <el-col :span="12">
                       <span>可用容量:{{scope.row.strmNum-scope.row.strmRenum}}</span>
                     </el-col>
                   </el-row>
                  </template>
                </el-table-column>
                <el-table-column label="需入库数量" align="center" prop="bpsNum" :width="50"/>
                <el-table-column label="已入库数量" align="center" prop="bpsRenum" :width="50"/>
                <el-table-column label="入库日期" align="center" prop="bpsDate" width="150px">
                  <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.bpsDate, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="入库数量">
                  <template slot-scope="scope">
                    <el-input-number id="inputNumber"
                                     v-model:value="scope.row.num"
                                     :min="0"
                                     :max="scope.row.bpsNum-scope.row.bpsRenum"
                                     :precision="2"/>
                  </template>
                </el-table-column>
<!--                <el-table-column label="价格" prop="">-->
<!--                </el-table-column>-->
<!--                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--                  <template slot-scope="scope">-->
<!--                    <el-button  size="mini" type="text" icon="el-icon-check">入库</el-button>-->
<!--                  </template>-->
<!--                </el-table-column>-->
              </el-table>
            </el-card>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </div>
    </el-tab-pane>
    <el-tab-pane label="完工入库" name="second">
      <child1 v-if="isChildUpdate2"></child1>
    </el-tab-pane>
<!--    <el-tab-pane label="销售退货" name="third">-->
<!--      <child2 v-if="isChildUpdate3" ></child2>-->
<!--    </el-tab-pane>-->
  </el-tabs>
</template>

<script>
import { listPut_storage, getPut_storage, delPut_storage, addPut_storage, updatePut_storage, updatePsg,getPsg} from "@/api/mes/put_storage";
import {listStoreroom} from "@/api/mes/storeroom";
import {listOrder} from "@/api/mes/order";
import firstComponent from './warehousingAsFinished'
import secondComponent from './salesReturns'

export default {
  name: "Put_storage",
  dicts:["storage_put_status","storage_bpstype"],
  components: {
    child1: firstComponent,
    child2: secondComponent,
  },
  data() {
    return {
      Index:0,
      // 默认第一个选项卡
      activeName: 'first',
      // 初始化两个变量 isChildUpdate1:true，isChildUpdate2:false；
      // 使用v-if控制child1和child2是否渲染。
      // 每次切换tab选项的时候，触发事件。让当前点击的tab变量设置位true，让当前组件重新渲染。
      // 这时候当你来回切换的时候，通过v-if判断是否重新渲染当前组件
      isChildUpdate2: true,
      isChildUpdate3: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库管理表格数据
      put_storageList: [],
      //库房列表
      storeroomList:[],
      //订单列表
      orderMatList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bpsSn: null,
      },
      queryParamsStrm: {
        sn: null,
        name: null,
      },
      queryParamsOrder: {
        name: null,
        userId: null,
        btsState: null,
        createdBy: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getStrmList();
    // this.getOrderList();
  },
  methods: {
    handleRenumChange(num){
      this.form.num=this.form.bpsRenum+num;
      console.log("afdafa",this.form.num)
    },
    handleStrmChange(row){
      row.strmId=parseInt(row.strmId)
      const selectedStrm = this.storeroomList.find(option => option.id === row.strmId);
      if (selectedStrm) {
        // console.log(selectedStrm, "selectedStrm!")
        // 更新其他输入框的值
        row.strmNum = selectedStrm.strmNum;
        row.strmRenum = selectedStrm.strmRenum;

      }
    },

    handleClick (tab) {
      if (tab.name === 'second') {
        this.isChildUpdate2 = true
        this.isChildUpdate3 = false
      } else if (tab.name === 'third') {
        this.isChildUpdate2 = false
        this.isChildUpdate3 = true
      }
    },
    /** 查询入库管理列表 */
    getList() {
      this.loading = true;
      const bpsType = 0;
      listPut_storage(this.queryParams).then(response => {
        this.put_storageList = response.rows;
        this.put_storageList = this.put_storageList.filter(item => item.bpsType == bpsType)
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询入库管理列表 */
    getStrmList() {
      listStoreroom(this.queryParamsStrm).then(response => {
        this.storeroomList = response.rows;
        const strmType = 0;
        this.storeroomList = this.storeroomList.filter(item => item.strmType == strmType)
      });
    },
    // /** 查询采购入库详情列表 */
    // getOrderList() {
    //   this.loading = true;
    //   listOrder(this.form.purchaseSn).then(response => {
    //     this.orderList = response.rows;
    //   });
    // },


    // /** 计算列表编号 */
    // calculateIndex() {
    //   this.put_storageList.forEach((item, index) => {
    //     this.$set(item, 'number', index + 1);
    //   });
    // },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        bpsSn: null,
        proStrmId: null,
        bpsNum: null,
        bpsType: null,
        bpsDate: null,
        isDeleted: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedDate: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加入库管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row,index) {
      this.reset();
      const id = row.id || this.ids
      this.Index=index
      getPut_storage(id).then(response => {
        this.form = response.data;
        getPsg(this.form.purchaseSn).then(reponse =>{
          this.orderMatList = reponse.rows;
          console.log(this.orderMatList)
        });
        this.open = true;
        this.title = "采购入库确认";
      });
    },
    /** 提交按钮 */
    submitForm() {
      var bpsNum=0
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.orderMatList.forEach((item)=>{
              bpsNum=bpsNum+item.bpsNum;
              this.form.num=this.form.num+item.num;
              item.purchaseSn=this.form.purchaseSn;
            });
            if(this.form.bpsNum<bpsNum){
              this.form.bpsNum=bpsNum;
            }
            if((this.form.bpsRenum+this.form.num)<this.form.bpsNum){
              this.form.state=1;
            }
            else{
              this.form.state=2;
            }
            this.form.bpsRenum=this.form.bpsRenum+this.form.num
            console.log("54564869", this.form.bpsRenum)
            updatePut_storage(this.form).then(response => {
              updatePsg(this.orderMatList).then(response =>{
                this.$modal.msgSuccess("修改成功");
                this.getStrmList();
              });
              this.open = false;
              this.getList();
            });
          } else {
            addPut_storage(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除入库管理编号为"' + ids + '"的数据项？').then(function() {
        return delPut_storage(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/put_storage/export', {
        ...this.queryParams
      }, `put_storage_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
